package com.rock;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HttpsUtil {

    /**
     * 
     */
    private static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession sslsession) {
            System.out.println("WARNING: Hostname is not matched for cert.");
            return true;
        }
    };

    /**
     * Ignore Certification
     */
    private static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {

        private X509Certificate[] certificates;

        @Override
        public void checkClientTrusted(X509Certificate certificates[], String authType) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = certificates;
                System.out.println("init at checkClientTrusted");
            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] ax509certificate, String s) throws CertificateException {
            if (this.certificates == null) {
                this.certificates = ax509certificate;
                System.out.println("init at checkServerTrusted");
            }
            // for (int c = 0; c < certificates.length; c++) {
            // X509Certificate cert = certificates[c];
            // System.out.println(" Server certificate " + (c + 1) + ":");
            // System.out.println("  Subject DN: " + cert.getSubjectDN());
            // System.out.println("  Signature Algorithm: "
            // + cert.getSigAlgName());
            // System.out.println("  Valid from: " + cert.getNotBefore());
            // System.out.println("  Valid until: " + cert.getNotAfter());
            // System.out.println("  Issuer: " + cert.getIssuerDN());
            // }

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    };

    public static String getMethod(String urlString, Map<String, String> headers) {

        ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
        try {
            URL url = new URL(urlString);
            /*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            // HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            Set<String> keys = headers.keySet();
            for (String key : keys) {
                connection.setRequestProperty(key, headers.get(key));
            }

            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);

            InputStream reader = connection.getInputStream();
            byte[] bytes = new byte[512];
            int length = reader.read(bytes);

            do {
                buffer.write(bytes, 0, length);
                length = reader.read(bytes);
            } while (length > 0);

            // result.setResponseData(bytes);
            reader.close();

            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        String repString = new String(buffer.toByteArray());
        return repString;
    }

    public static void main(String[] args) {
        String urlString = "https://aduatl62.morningstar.com/PortfolioAnalysis/UserWorkbenchProfile.do?isSingleWindow=false&token=VVpbkDIh6+TgwA5OccfLEs9S6xU8AyJ6dpCBkFiwmMA2PhCTXp7OFA==&product=PA&currentDate=2014-10-15&_=1413337421049";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(
                "Cookie",
                "JSESSIONID=2C348BBD997A549AC5815D87E13763AF; JSESSIONID=2C348BBD997A549AC5815D87E13763AF; Persistent_id_H9Lmf5qrjCdTWX=0CCA05AC0CD4:1406181808; s_pers=%20s_nr%3D1406182017571-New%7C1408774017571%3B%20s_lv%3D1406182017576%7C1500790017576%3B%20s_lv_s%3DFirst%2520Visit%7C1406183817576%3B; fp=00314128465724850; paCases=1; qs_wsid=W_IYP96O0MESM1ZL3AKZM77O3352642729_1; qs_wsid_live=W_O8QSK5L1YO7YJOHND3XNMS3354079682_1; __utma=153686052.2007651553.1405068687.1413338883.1413354086.52; __utmc=153686052; __utmz=153686052.1413354086.52.43.utmcsr=aduatl62.morningstar.com|utmccn=(referral)|utmcmd=referral|utmcct=/PortfolioA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6BowOd8z84CQD6tUNWw&h=bNWaym364B7/8kgBWBwvWg&i2=DIRECT&st=41927.056655&t=41927.056655; awdsec30=c=69Myosw8ENIfWr5gZ/KTCkA784sMzXSOamtGgJdGEKR11/04j+hOLArRToGSAGxE7WYDd0C7DZWGCwaYihW9KKEnJce/Wo6nWQwJ4W3ZVxhZyc/Ma3jxy1F9uxCv+pb7aeepEHyQE6mFQ2AD6wpeVTH4GCpjh4y/MHuDRydeuE/ru/5/lqYCTT5Ium2slgIoDJshvQk7MSs9iyqzD/nEvVyq9D+1osQBzbPXjJrPY+Kzt4Azrcqw2ndJAAn6t65p8IjTFRuJCW2T9mYhqtejRiRUiPRg91+qacvuxfvBXti7Ey+ZT1zLlPETQlXXkuwwgNaPIKSwhpJBIuOgq6BrLgeuV3X+cIC6aBXcKm8z00kiCOsJsee/Cv8tUj3wJTpO76ttjnPwfP/kx1hGXKreRftQr9Z2xLCXsRytFrT0CItU0KT0apDzsJTkr5YkxCx0bEmAr9lyZTpFQLFaw6yDp8NMupo9IN9ZmIp6BowOd8z84CQD6tUNWw&h=bNWaym364B7/8kgBWBwvWg&i2=DIRECT&st=41927.056655&t=41927.056655; advtnonsecure=NM2NPLL69O4PP04P17NPPN4638795359M3P08P0MN9M3128P478359K7P301L7804M1P23O8LN14N489KPLNL4939425695P; advtsecure=L8POK2LMM49NKK8N3N00M0M811K2M81KM5L4L137P33P827O545M5L55O275700P201NPL42PKPP9L579726730P1N9P08190K43973LN80208K478K26N5800K855KO; LoginID=9244e79d-8c22-4b60-9aec-20c25f052a06; srtqs=8346821527; Instid=MSPA");
        String output = new String(HttpsUtil.getMethod(urlString, headers));
        System.out.println(output);
    }
}